//
//  ClerkManagerViewController.m
//  tryshopping.boss
//
//  Created by Mr.Lee on 2017/3/23.
//  Copyright © 2017年 Reabam. All rights reserved.
//

#import "ClerkManagerViewController.h"
#import "ClerkManagerListCell.h"            // cell
#import "StoreAssistantModel.h"             // model
#import "IdentityChangeViewController.h"    // 身份信息变更
#import "StaffSearchViewController.h"

@interface ClerkManagerViewController () <UITableViewDelegate, UITableViewDataSource, ClerkManagerListCellDelegate, UIGestureRecognizerDelegate>
@property (weak, nonatomic)  UITableView *tableV;
// 记录最后一个
@property(nonatomic,strong)NSIndexPath *lastPath;
/** 总数 */
@property (nonatomic, copy) NSString* TotalCount;
/** 数据数组 */
@property (nonatomic, strong) NSMutableArray *modelArray;

@end

@implementation ClerkManagerViewController
{
    NSInteger current;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = _titleName;
    
    UIImage *img=[UIImage imageNamed:@"sousuo"];
    UIImage *tinted = [img rt_tintedImageWithColor:[UIColor whiteColor]];
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0, 60/2, 60/2)];
    [searchBtn setImage:tinted forState:UIControlStateNormal];
    [searchBtn setImage:tinted forState:UIControlStateHighlighted];
    [searchBtn addTarget:self action:@selector(searchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* searchBtnItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
    self.navigationItem.rightBarButtonItem = searchBtnItem;

    current = -1;
    self.modelArray = [NSMutableArray array];
    [self setUpTableView];
    // 加载数据
    [self requestData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UPDATECOMPANYLIST) name:@"UPDATECOMPANYLIST" object:nil];
    
}
- (void)UPDATECOMPANYLIST{
    [self requestData];
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UPDATECOMPANYLIST" object:nil];
}

- (void)setUpTableView{
    
    UITableView *tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64) style:UITableViewStylePlain];
    self.tableV = tableV;
    tableV.backgroundColor = [UIColor whiteColor];
    tableV.dataSource = self;
    tableV.delegate = self;
    tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView *emputyView = [[UIView alloc] init];
    tableV.tableFooterView = emputyView;
    [self.view addSubview:tableV];
    
    
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1; //几个手指点击
    tableViewGesture.delegate = self;
    tableViewGesture.cancelsTouchesInView = NO;//是否取消点击处的其他action
    [tableV addGestureRecognizer:tableViewGesture];
}

// 给tableview加点击手势，实现手势的代理，不然点击cell会没有反应。
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UITableView class]]) {
        return YES;
    }
    return  NO;
}
- (void)tableViewTouchInSide {
    [self oldCellMoreViewHide];
}

- (void)searchBtnClick:(UIButton *)sender{
    StaffSearchViewController *vc = [[StaffSearchViewController alloc] init];
    vc.companyId = self.companyId;
    vc.titleName = self.titleName;
    vc.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- 网络请求
- (void)requestData{
    NSString *Token = [UserDefaults objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:self.companyId forKey:@"companyId"];
    NSLog(@"-----requestDataParams---- %@", params);
    [MBProgressHUD showIndeterminateHudSub:@"加载中，请稍候。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"manage/findSysstaffList" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"findSysStaffCompList====%@",severDataDict.dataDict);
        if (isSuccess) {
            [self.modelArray removeAllObjects];
            [MBProgressHUD hideProgressHUDInternal:self.view];
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                NSMutableArray *dataArr = [severDataDict.dataDict objectForKey:@"users"];
                for (NSDictionary* dicc in dataArr ){
                    StoreAssistantModel *model = [StoreAssistantModel mj_objectWithKeyValues:dicc];
                    [self.modelArray addObject:model];
                }
                [self.tableV reloadData];
                
//                // 获取总数
//                self.TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];

            } else {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                
//                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
//                    LoginViewController *loginVC = [[LoginViewController alloc] init];
//                    [self.navigationController pushViewController:loginVC animated:YES];
//                }
            }
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            [MBProgressHUD showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];
}

#pragma mark  -- tableViewDatasource

#pragma mark - TableView DateSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
 
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.modelArray.count;

}
//每行的高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return  90;
}
// 返回每行cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    StoreAssistantModel *model = self.modelArray[indexPath.row];
    
    static NSString *CellIdentifier = @"cell2";
    ClerkManagerListCell *cell = ( ClerkManagerListCell *)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"ClerkManagerListCell" owner:nil options:nil] lastObject];
    }
    
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.index = indexPath ;
    cell.model = model;
    
    NSInteger row = [indexPath row];
    NSInteger oldRow = [self.lastPath row];
    if (row == oldRow && self.lastPath!=nil) {
        cell.moreView.hidden = NO;
        [cell moreViewShowWithNoAnimate];
    }else{
        cell.moreView.hidden  = YES;
        [cell moreViewHide];
    }
    return cell;
}

- (void)clickMoreBtn:(NSIndexPath *)index{
    NSInteger newRow = [index row];
    NSInteger oldRow = (self .lastPath !=nil)?[self .lastPath row]:-1;
    if (newRow != oldRow) {
        ClerkManagerListCell *newCell = ( ClerkManagerListCell *)[self.tableV cellForRowAtIndexPath:index];
        [newCell moreViewShow];
        ClerkManagerListCell *oldCell = ( ClerkManagerListCell *)[self.tableV cellForRowAtIndexPath:self.lastPath];
        [oldCell moreViewHide];
        self.lastPath = index;
    } else{
        ClerkManagerListCell *newCell = ( ClerkManagerListCell *)[self.tableV cellForRowAtIndexPath:index];
        [newCell moreViewShow];
        self.lastPath = index;
    }
    [self.tableV deselectRowAtIndexPath:index animated:YES];
}

#pragma mark - TableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self oldCellMoreViewHide];
    
//    ClerkManagerListCell *oldCell = ( ClerkManagerListCell *)[self.tableV cellForRowAtIndexPath:self.lastPath];
//    [oldCell moreViewHide];
//    self.lastPath = nil;

    
//    NSInteger newRow = [indexPath row];
//    NSInteger oldRow = (self .lastPath !=nil)?[self .lastPath row]:-1;
//    if (newRow != oldRow) {
//        ClerkManagerListCell *newCell = ( ClerkManagerListCell *)[tableView cellForRowAtIndexPath:indexPath];
//        newCell.view1.hidden = NO;
//        ClerkManagerListCell *oldCell = ( ClerkManagerListCell *)[tableView cellForRowAtIndexPath:self.lastPath];
//        oldCell.view1.hidden = YES;
//        self.lastPath = indexPath;
//    }
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}




#pragma mark -- ClerkManagerListCellDelegate
// 点击启用
- (void)leftBtnClick:(NSIndexPath *)index{
    [self oldCellMoreViewHide];
    StoreAssistantModel *model = self.modelArray[index.row];
    [self updateStateOrIdentityRequestWithscID:model.scId andStatus:@"Y"];
}
// 点击停用
- (void)middleBtnClick:(NSIndexPath *)index{
    [self oldCellMoreViewHide];
    StoreAssistantModel *model = self.modelArray[index.row];
    [self updateStateOrIdentityRequestWithscID:model.scId andStatus:@"N"];
}

//点击身份变更
- (void)rightBtnClick:(NSIndexPath *)index{
    [self oldCellMoreViewHide];
    // 身份变更
    IdentityChangeViewController *identiChange = [[IdentityChangeViewController alloc] init];
    StoreAssistantModel *model = self.modelArray[index.row];
    __weak typeof(self) weakself = self;
    identiChange.IdentityChangeViewControllerBlock = ^(NSString *identityString){
        [weakself requestData];
//        model.userTypeName = identityString;
//        [weakself.tableV reloadData];
    };
    identiChange.titleName = model.userTypeName;
    identiChange.userType = model.userType;
    identiChange.scId = model.scId;
    identiChange.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:identiChange animated:YES];
    
}

// 审核
- (void)gotoCheckIdentity:(NSIndexPath *)index{
    StoreAssistantModel *model = self.modelArray[index.row];
    NSLog(@"%ld---%ld", index.section, index.row);
    //显示弹出框列表选择
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确认通过审核?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* saveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
//        StoreAssistantModel *model = self.modelArray[index.row];
        [self updateStateOrIdentityRequestWithscID:model.scId andStatus:@"Y"];
    }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
    }];
    
    [cancleAction setValue:[UIColor lightGrayColor] forKey:@"titleTextColor"];
    
    [alert addAction:cancleAction];
    [alert addAction:saveAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}

// 移除'更多操作'
- (void)oldCellMoreViewHide{
    ClerkManagerListCell *oldCell = ( ClerkManagerListCell *)[self.tableV cellForRowAtIndexPath:self.lastPath];
    [oldCell moreViewHide];
    self.lastPath = nil;
}

// 修改店员状态或者身份
- (void)updateStateOrIdentityRequestWithscID:(NSString *)scId andStatus:(NSString *)status{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:scId forKey:@"scId"];
    [params setValue:status forKey:@"status"];
    NSLog(@"params ==== %@",params);
    [HttpRequest requestData:@"manage/auditUser" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"====%@",severDataDict.dataDict);
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATECOMPANYLIST" object:nil];
                // 刷新数据
                [self requestData];
                
                
            }else{
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHud:requestResultStr view:self.view];
//                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
//
//                    LoginViewController* Login=[[LoginViewController alloc]init];
//                    [self.navigationController pushViewController:Login animated:YES];
//
//                }
            }
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            [MBProgressHUD showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
}


@end
